package com.deyuanyun.pic.pipe.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.tool.JXL;
import com.deyuanyun.pic.common.util.ChinaInitial;
import com.deyuanyun.pic.common.util.MapUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.mapper.base.UnifiedEncodingMapper;
import com.deyuanyun.pic.pipe.domain.exceldomain.ValveRoomImportDemo;
import com.deyuanyun.pic.pipe.mapper.DyyValveRoomMapper;
import com.deyuanyun.pic.pipe.service.ValveRoomService;
import com.deyuanyun.pic.pipe.support.utils.ValveRoomCenterPoint;
import com.deyuanyun.pic.support.biz.CodeUtil;
import com.github.pagehelper.Page;

/**
 * 
 * @ClassName ValveRoomServiceImpl
 * @Description 管道基础数据 ->战场阀室service实现
 * @author 王敏
 * @date 2015年1月18日
 */
@Service("valveRoomService")
public class ValveRoomServiceImpl implements ValveRoomService {

	@Resource
	private DyyValveRoomMapper dyyValveRoomMapper;
	
	@Resource
	private UnifiedEncodingMapper unifiedEncodingMapper;


	@Override
	public Page<HashMap<String, Object>> findPage(HashMap param) {
		Page<HashMap<String, Object>> page = dyyValveRoomMapper.findPage(param);
		for (HashMap<String, Object> m : page) {
			if(null!=m.get("TYPE_")){
			m.put("TYPE_", CodeUtil.getName((String) m.get("TYPE_")));
		}
		}
		MapUtil.emptyConvert(page);
		return page;
	}


	public String importData(List<ValveRoomImportDemo> data) throws Exception {
		Map<String, Object> bean = null;
		// 根据名称分类场站阀室
		Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
		for (ValveRoomImportDemo info : data) {
			// 阀室类型
			// info.setSiteType(CodeUtil.getCodeId("", name));
			bean = MapUtil.beanToMap(info);
			bean.put("id", UUID.randomUUID().toString().replaceAll("-", ""));
			bean.put("createDate", StringUtils.convertDateToString(
					new Date(), StringUtils.DATE_TIME_DEFAULT));
			bean.put("createUser", "");
			if (map.containsKey(info.getSiteName())) {
				List<Map<String, Object>> list = map
						.get(info.getSiteName());
				bean.put("roomId", list.get(0).get("roomId"));
				bean.put("sort", list.size());
				list.add(bean);
			} else {
				List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
				bean.put("sort", 0);
				bean.put("roomId", info.getSiteName());
				list.add(bean);
				map.put(info.getSiteName(), list);
				
			}
			
		}
		
		
		Properties p= TempStoreDataSupport.pullDataf("application.properties");
		String companyCode=p.getProperty("companyCode");// 公司代码
		
		
		StringBuffer result=new StringBuffer();
		Iterator<String> it=map.keySet().iterator();
		while(it.hasNext())
		{
			String key=it.next();
			if(map.get(key).size()<3){
				result.append("阀室信息").append("GIS 坐标信息不足3条，不能导入");
			}
		}
		if(result.length()>0)
		{
			return result.toString();
		}
		
		
		for(List<Map<String, Object>> d:map.values())
		{
			
			
			if(d.size() > 0)
			{
				Map<String, Object> info=d.get(0);
				Map<String, Object> m=dyyValveRoomMapper.findInfo((String)info.get("siteName"));
				
				
				if(StringUtils.isEmpty((String)m.get("CODE")))
				{
					//不存在code 即场站阀室详情无数据
					String roomName=(String) m.get("SHOW_NAME");
					String code=companyCode+m.get("ABRIDGE");//ChinaInitial.getPYIndexStr(roomName.length()>=2?roomName.substring(0,2):roomName, true);
					
//					String type=(String) m.get("TYPE_");
//					String id=CodeUtil.getCodeId("SITE_TYPE", "阀室");
//					if(type == null || !type.equals(id))
//					{
//						code+="Z";
//					}
					info.put("code", code);
					
					
					dyyValveRoomMapper.insertData(info);
					
				}
				
				//检查gis数据是否已经导入
				HashMap<String,Object> param=new HashMap<String,Object>();
				param.put("id", (String)info.get("siteName"));
				List<HashMap<String, Object>> checkResult=dyyValveRoomMapper.findPage(param);
				if(checkResult.size() == 1)
				{
					BigDecimal gisNum=(BigDecimal) checkResult.get(0).get("GISNUM");
					if(gisNum.intValue() >0)
					{
						result.append(checkResult.get(0).get("SITE_NAME")).append("地理坐标信息导入失败，原因：数据库已经导入该场站阀室地理坐标信息。");
						continue;
					}
				}
				
			}
			for(Map<String, Object> m:d)
			{
				dyyValveRoomMapper.insertPosit(m);
			}
			
		}

		return result.length()>0?result.toString():null;
	}


	@Override
	public int delGis(Map map) {
		dyyValveRoomMapper.delGisInfo(map);
		return dyyValveRoomMapper.delGis(map);
	}

	@Override
	public int delInfo(Map map) {
		return dyyValveRoomMapper.delInfo(map);
	}

	@Override
	public List<List<String[]>> excelExport(Map param) {
		Page<LinkedHashMap<String, Object>> data = dyyValveRoomMapper.findPageExport(param);
		
		
		
		List<List<String[]>> result=new ArrayList<List<String[]>>();
		List<String[]> lsr = JXL.toList(data, "yyyy-MM-dd HH:mm:ss");
		result.add(lsr);
		return result;
	}


	@Override
	public List<Map<String, Object>> findGis(String roomId) {
		return dyyValveRoomMapper.findGis(roomId);
	}


	@Override
	public void updateCenterPoint() throws Exception {
		List<String> rooIdList=dyyValveRoomMapper.getNoCenterPointRoom();
		
		if(rooIdList != null )
		{
			for(String roomId:rooIdList)
			{
//				System.out.println("============>"+roomId);
				 List<Map<String, Object>>  gisList=dyyValveRoomMapper.getRoomGisPoint(roomId);
				 if(gisList != null && gisList.size() >= 4 )
				 {
					 Map<String,Object> map=ValveRoomCenterPoint.getCenterPoint(gisList);
					 map.put("roomId", roomId);
					 map.put("id", UUID.randomUUID().toString().replaceAll("-", ""));
					 dyyValveRoomMapper.setRoomCenterPoint(map);
				 }
				
			}
		}
		
	}


	@Override
	public List<HashMap<String, Object>> findValveRoomCenterPoint() {
		return dyyValveRoomMapper.findValveRoomCenterPoint();
	}


	@Override
	public Map<String, Object> findValveRoomCenterPointById(String roomId) {
		return dyyValveRoomMapper.findValveRoomCenterPointById(roomId);
	}

}
